package com.spring.bean.demo1;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

public class SpringDemo1 {
    @Test
    public void demo1 () {
        // UserService userService = new UserServiceImpl();
        UserServiceImpl userService = new UserServiceImpl();
        userService.setName("Kinaco");
        userService.sayHello();
    }

    @Test
    /**
     * 使用 Spring 的方式实现
     */
    public void demo2 () {
        // 创建 Spring 工厂
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 通过工厂获得类
        UserService userService = (UserService) applicationContext.getBean("userService");
        // 通过类实例调用方法
        userService.sayHello();
    }

    @Test
    /**
     * 读取磁盘系统中的配置文件
     */
    public void demo3 () {
        // 创建 Spring 的工厂类
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("F:\\applicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.sayHello();
    }

    @Test
    /**
     * 传统方式创建工厂类
     */
    public void demo4 () {
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
        UserService userService = (UserService) beanFactory.getBean("userService");
        userService.sayHello();
    }

    @Test
    /**
     * 传统方式创建工厂类，读取磁盘系统中的配置文件
     */
    public void demo5 () {
        BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("F:\\applicationContext.xml"));
        UserService userService = (UserService) beanFactory.getBean("userService");
        userService.sayHello();
    }
}
